package com.av.bcacc.javaapi.thread.ticket;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @description 同步代码块实现线程安全的买票程序
 * @author weiliang hu
 * @time 2021/7/17 17:16
 * @email:2072025612@qq.com
 */

public class TicketLockRunnable implements Runnable {

    private int ticketCount = 100;//票的数量
    private Object object = new Object();//多个线程必须使用同一把锁，

    @Override
    public void run() {
        while (true) {
            synchronized (object) {//任意对象即可，需要时唯一的锁对象
                if (ticketCount <= 0) {
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ticketCount--;
                System.out.println(Thread.currentThread().getName() + "在售票，还剩" + ticketCount + "张票");
            }
        }

    }
}
